package com.yunshipei.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.yunshipei.model.YspEvent;

import io.rong.eventbus.EventBus;


public class NetChangedReceiver extends BroadcastReceiver {

    public NetChangedReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo == null || !activeNetInfo.isConnected() || !activeNetInfo.isAvailable()) {
            YspEvent.NetChangeEvent event = new YspEvent.NetChangeEvent();
            event.setNetConnected(false);
            EventBus.getDefault().post(event);
            return;
        }
        int netType = activeNetInfo.getType();
        if (netType == ConnectivityManager.TYPE_MOBILE) {
            EventBus.getDefault().post(new YspEvent.NetChangeEvent(false));
            return;
        }

        if (netType == ConnectivityManager.TYPE_WIFI) {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            String ssId = wifiInfo.getSSID();
            EventBus.getDefault().post(new YspEvent.NetChangeEvent(true, ssId.substring(1, ssId.length() - 1)));
        }
    }
}
